package org.linearlist;

/**
 * @author: 默苍璃
 * @date: 2023-04-11 10:29
 * <p>
 * 链栈
 */
public class LinkStack<T> {

    /**
     * 栈顶指针
     */
    private Node<T> top;

    /**
     * 存储栈的长度
     */
    private int length;


    /**
     * 构造一个空的栈
     */
    public LinkStack() {
        length = 0;
        top = null;
    }

    public void push(T obj)                 //入栈
    {
        top = new Node<T>(obj, top);
        length++;
    }

    public T pop()                          //出栈
    {
        if (top == null) {
            System.out.println("栈已空，无法删除元素！");
            return null;
        }
        T x = top.data;
        top = top.next;
        length--;
        return x;
    }

    public T getHead()                      //取栈顶数据元素
    {
        if (top == null) {
            System.out.println("栈已空，无法读取元素！");
            return null;
        }
        return top.data;
    }

    public int size()                       //求出栈中数据元素的个数
    {
        return length;
    }

    public boolean isEmpty()       //判断当前栈是否为空
    {
        return top == null;
    }

    public void nextOrder()        //依次访问栈中每个元素并输出
    {
        Node<T> p = top;
        while (p != null) {
            System.out.println(p.data);
            p = p.next;
        }
    }

    public void clear()             //销毁一个已存在的栈
    {
        top = null;
    }
}